package cn.lblbc.webbrowser

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import cn.lblbc.webbrowser.utils.PasswordManager

class CalculatorActivity : BaseActivity() {
    private lateinit var display: TextView
    private var currentNumber = "0"
    private var shouldResetDisplay = false
    private lateinit var passwordManager: PasswordManager
    private var inputSequence = ""
    private var isPasswordGate = false
    
    // 计算器功能相关变量
    private var firstOperand: Double = 0.0
    private var operator: String = ""
    private var isOperatorPressed = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_calculator)

        isPasswordGate = intent.getBooleanExtra("IS_PASSWORD_GATE", false)
        
        // 设置状态栏颜色与背景一致
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.parseColor("#121212")
        }
        
        passwordManager = PasswordManager(this)
        display = findViewById(R.id.display)
        updateDisplay()
        
        // 设置按钮点击监听器
        setupButtonListeners()
    }
    
    private fun setupButtonListeners() {
        // 数字按钮
        findViewById<View>(R.id.btn0).setOnClickListener { onNumberClick("0") }
        findViewById<View>(R.id.btn1).setOnClickListener { onNumberClick("1") }
        findViewById<View>(R.id.btn2).setOnClickListener { onNumberClick("2") }
        findViewById<View>(R.id.btn3).setOnClickListener { onNumberClick("3") }
        findViewById<View>(R.id.btn4).setOnClickListener { onNumberClick("4") }
        findViewById<View>(R.id.btn5).setOnClickListener { onNumberClick("5") }
        findViewById<View>(R.id.btn6).setOnClickListener { onNumberClick("6") }
        findViewById<View>(R.id.btn7).setOnClickListener { onNumberClick("7") }
        findViewById<View>(R.id.btn8).setOnClickListener { onNumberClick("8") }
        findViewById<View>(R.id.btn9).setOnClickListener { onNumberClick("9") }
        
        // 操作按钮
        findViewById<View>(R.id.btnClear).setOnClickListener { onClearClick() }
        findViewById<View>(R.id.btnEquals).setOnClickListener { onEqualsClick() }
        
        // 运算符按钮
        findViewById<View>(R.id.btnAdd).setOnClickListener { onOperatorClick("+") }
        findViewById<View>(R.id.btnSubtract).setOnClickListener { onOperatorClick("-") }
        findViewById<View>(R.id.btnMultiply).setOnClickListener { onOperatorClick("×") }
        findViewById<View>(R.id.btnDivide).setOnClickListener { onOperatorClick("÷") }
        
        // 小数点按钮
        findViewById<View>(R.id.btnDecimal).setOnClickListener { onDecimalClick() }
        
        // 其他按钮（在伪装计算器中不实现功能）
        findViewById<View>(R.id.btnPlusMinus).setOnClickListener {  }
        findViewById<View>(R.id.btnPercent).setOnClickListener {  }
    }
    
    private fun onNumberClick(number: String) {
        // 输入数字时检查密码
        inputSequence += number
        
        // 如果输入序列超过密码长度，则只保留最后几位
        val password = passwordManager.getPassword()
        if (inputSequence.length > password.length) {
            inputSequence = inputSequence.substring(inputSequence.length - password.length)
        }
        
        // 检查是否输入了正确的密码
        if (inputSequence == password) {
            if (isPasswordGate) {
                finish()
            } else {
                // 密码正确，启动主浏览器Activity
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish() // 关闭计算器Activity
            }
            return
        }
        
        // 更新显示
        if (currentNumber == "0" || shouldResetDisplay) {
            currentNumber = number
            shouldResetDisplay = false
        } else {
            currentNumber += number
        }
        updateDisplay()
    }
    
    private fun onClearClick() {
        currentNumber = "0"
        inputSequence = ""
        updateDisplay()
    }
    
    private fun onEqualsClick() {
        // 在伪装计算器中不实现计算功能
        // Toast.makeText(this, "计算器功能受限", Toast.LENGTH_SHORT).show()
        
        // 执行计算
        if (isOperatorPressed) {
            val result = calculate(firstOperand, operator, currentNumber.toDouble())
            currentNumber = formatResult(result)
            operator = ""
            isOperatorPressed = false
            shouldResetDisplay = true
            updateDisplay()
        }
    }
    
    private fun updateDisplay() {
        display.text = currentNumber
    }
    
    private fun onOperatorClick(op: String) {
        if (isOperatorPressed) {
            onEqualsClick()
        }
        
        firstOperand = currentNumber.toDouble()
        operator = op
        isOperatorPressed = true
        shouldResetDisplay = true
    }
    
    private fun onDecimalClick() {
        if (shouldResetDisplay) {
            currentNumber = "0"
            shouldResetDisplay = false
        }
        
        if (!currentNumber.contains(".")) {
            currentNumber += "."
            updateDisplay()
        }
    }
    
    private fun calculate(first: Double, operator: String, second: Double): Double {
        return when (operator) {
            "+" -> first + second
            "-" -> first - second
            "×" -> first * second
            "÷" -> first / second
            else -> second
        }
    }
    
    private fun formatResult(result: Double): String {
        // 如果结果是整数，不显示小数点
        return if (result == result.toLong().toDouble()) {
            result.toLong().toString()
        } else {
            result.toString()
        }
    }

    override fun onBackPressed() {
        if (isPasswordGate) {
            // If it's a password gate, pressing back should not reveal the content.
            // It should act like pressing the home button.
            moveTaskToBack(true)
        } else {
            super.onBackPressed()
        }
    }
}